package com.example.blog.demos.web.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * @author Q
 * @create 2025-06-22-13:28
 */
@Slf4j
public class SecurityUtils {
    /**
     * 加密
     * @throws UnsupportedEncodingException
     */
    public static String encrypt(String password) throws UnsupportedEncodingException {
        String salt = UUID.randomUUID().toString().replace("-","");
        //md5(salt+password)
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        //数据库存储  盐值+密文
        return salt+ secretString;
    }

    /**
     * 解密
     * @throws UnsupportedEncodingException
     */
    public static Boolean verify(String password, String finalPassword) {
        if (finalPassword==null || finalPassword.length()!=64){
            log.error("密码长度不足");
            return false;
        }
        String salt = finalPassword.substring(0,32);
        //md5(salt+password)
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.error("getBytes 异常, e:", e);
            throw new RuntimeException(e);
        }
        //数据库存储  盐值+密文
        return (salt+secretString).equals(finalPassword);
    }
}
